﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Business
{
    public partial class ProjectChannel
    {
        public static Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE Update(
                    ref string messageError,
                    ref List<ProjectChannel> listOldPC,
                    ref Common.UserInfo UserInfo)
        {
            DataClassesDataContext context = null;
            try
            {
                context = new DataClassesDataContext(Common.Global.GetConnectionInfo().ConnectionStringSQL);

                listOldPC = listOldPC.GroupBy(x => new { x.ProjectID, x.ProjectMechanicism, x.Channel })
                  .Select(group => group.First()).ToList();

                //init
                List<ProjectChannel> listNewPC = new List<ProjectChannel>();
                //add new
                foreach (ProjectChannel item in listOldPC)
                {
                    var query = context.ProjectChannels.Where(p => p.ProjectID == item.ProjectID && p.ProjectMechanicism == item.ProjectMechanicism);
                    context.ProjectChannels.DeleteAllOnSubmit(query);

                    ProjectChannel pc = new ProjectChannel();
                    pc.ProjectID = item.ProjectID;
                    pc.ProjectMechanicism = item.ProjectMechanicism;
                    pc.Channel = item.Channel;
                    pc.NoLocation = 0;//item.NoLocation;
                    pc.NoWorkingDayPerLocation = 0;// item.NoWorkingDayPerLocation;
                    pc.NoSessionPerDay = 0;// item.NoSessionPerDay;
                    pc.AveTrafficPerDay = 0;// item.AveTrafficPerDay;
                    pc.Timing = 1;
                    pc.Status = (int)Common.STATUS_CODE.ROW_STATUS.ACTIVE;
                    pc.CreatedBy = UserInfo.UserID;
                    pc.CreatedDateTime = DateTime.Now;
                    pc.RowVersion = 1;

                    listNewPC.Add(pc);
                    context.ProjectChannels.InsertOnSubmit(pc);
                }

                context.SubmitChanges();

                listOldPC = listNewPC;

                return Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS;
            }
            catch
            {
                messageError = Common.EnumUtils.stringValueOf(Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT.SYSTEM_ERROR);
                return Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SYSTEM_ERROR;
            }
            finally
            {
                context = null;
            }
        }
    }
}
